<!-- src/views/HomeView.vue -->
<template>
  <div class="home-container">
    <AppNavbar @search="handleSearch" v-model:searchKey="searchKey" />
    <main class="video-main">

      <!-- 轮播图区域 -->
      <el-carousel height="300px" class="carousel" :interval="5000" arrow="always">
        <el-carousel-item v-for="(item, index) in carouselItems" :key="index">
          <div class="carousel-item" :style="{ backgroundImage: `url(${item.image})` }">
            <div class="carousel-content">
              <div class="carousel-title">{{ item.title }}</div>
              <div class="carousel-desc">{{ item.desc }}</div>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>

      <!-- 视频分类标签 -->
      <div class="video-categories">
        <el-scrollbar>
          <div class="category-tags">
            <el-tag
                :class="['category-tag', { active: activeCategory === 'all', disabled: loading }]"
                @click="handleCategoryChange('all')"
            >
              全部
            </el-tag>
            <el-tag
                v-for="category in categories"
                :key="category.id"
                :class="['category-tag', { active: activeCategory === category.id, disabled: loading }]"
                @click="handleCategoryChange(category.id)"
            >
              {{ category.name }}
            </el-tag>
          </div>
        </el-scrollbar>
      </div>

      <!-- 视频卡片 -->
      <div class="video-content-container">
        <transition name="fade" mode="out-in">
          <div v-if="!loading && videoList.length > 0" key="videos" class="video-content">
            <el-row :gutter="20" class="video-grid">
              <el-col
                  v-for="video in videoList"
                  :key="video.id"
                  :xs="24" :sm="12" :md="8" :lg="6" :xl="5"
              >
                <VideoCard :video="video" @click="handleVideoClick" />
              </el-col>
            </el-row>
          </div>

          <!-- 空数据状态 -->
          <div v-else-if="!loading && videoList.length === 0" key="empty" class="empty-state">
            <el-empty
              description="暂无视频数据"
              :image-size="200"
            >

            </el-empty>
          </div>

          <!-- 加载状态 -->
          <div v-else key="loading" class="loading">
            <el-icon class="loading-icon"><Loading /></el-icon>
          </div>
        </transition>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Loading } from '@element-plus/icons-vue'

import {apiUploadVideo,getMsg} from "@/api/file.js";
import { useRouter } from 'vue-router'
import AppNavbar from '@/components/AppNavbar.vue'
import VideoCard from '@/components/VideoCard.vue'
import {getAllVideos, getVideosByCategoryId} from "@/api/vidoe.js";
import {useVideoStore} from "@/api/stores/usevideoStore.js";
import {getCategories} from "@/api/category.js";
import {getInfo} from "@/api/user.js";
import {ElMessage} from "element-plus";

const router = useRouter()
const videoStore = useVideoStore()

// 响应式数据
const searchKey = ref('')
const videoList = ref([])
const loading = ref(false)
const hasMore = ref(true)
const activeCategory = ref('all') // 默认选中"全部"
const allVideos = ref([]) // 存储所有视频数据，避免重复请求
let page = 1




const carouselItems = ref([
  {
    image: 'http://sy9colix3.hn-bkt.clouddn.com/t1.jpg',
    title: 'Vue3从入门到实战',
    desc: '学习最新前端框架，构建现代化Web应用'
  },
  {
    image: 'http://sy9colix3.hn-bkt.clouddn.com/t2.jpg',
    title: 'Element Plus组件库深度解析',
    desc: '掌握Element Plus，提升开发效率'
  },
  {
    image: 'http://sy9colix3.hn-bkt.clouddn.com/t3.jpg',
    title: 'Bilibili风格网站开发实战',
    desc: '从0到1打造视频网站'
  }
]);


// 分类
const categories = ref([]);

// 处理分类变化
async function handleCategoryChange(categoryId) {
  if (activeCategory.value === categoryId || loading.value) return // 避免重复点击和加载中点击

  activeCategory.value = categoryId
  loading.value = true

  // 立即清空视频列表，避免显示旧数据
  videoList.value = []

  try {
    if (categoryId === 'all') {
      // 如果是"全部"，直接使用缓存的数据
      if (allVideos.value.length > 0) {
        videoList.value = [...allVideos.value]
      } else {
        // 如果缓存为空，重新请求
        await loadVideos()
      }
    } else {
      // 获取特定分类的视频
      await getCategoryVideos(categoryId)
    }
  } catch (error) {
    console.error('加载视频失败:', error)
    ElMessage.error('加载视频失败')
  } finally {
    loading.value = false
  }
}

// 根据分类的Id来查找该分类下的视频
async function getCategoryVideos(cid) {
  try {
    const res = await getVideosByCategoryId(cid)
    if (res.code === 200) {
      videoList.value = res.videos || []
    } else {
      ElMessage.error(res.msg || '获取分类视频失败')
      videoList.value = []
    }
  } catch (error) {
    console.error('获取分类视频失败:', error)
    ElMessage.error('获取分类视频失败')
    videoList.value = []
  }
}

// 加载所有视频
async function loadVideos() {
  loading.value = true
  try {
    const res = await getAllVideos()
    if (res.code === 200) {
      videoList.value = res.videos || []
      allVideos.value = [...res.videos] // 缓存所有视频数据
    } else {
      ElMessage.error(res.msg || '加载视频失败')
      videoList.value = []
    }
  } catch (error) {
    console.error('加载视频失败:', error)
    ElMessage.error('加载视频失败')
    videoList.value = []
  } finally {
    loading.value = false
  }
}

async function getCate() {
  try {
    const res = await getCategories()
    if (res.code === 200) {
      categories.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取分类失败')
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类失败')
  }
}

// 搜索处理
const handleSearch = () => {
  videoList.value = []
  page = 1
  hasMore.value = true
  // loadVideos()
}

const handleVideoClick = (video) => {
  videoStore.selectVideo(video)
  router.push({
    path: `/video/${video.id}`,
  })
}

async function getUserInfo() {
  try {
    const res = await getInfo()
    if (res.code === 200) {
      localStorage.setItem("user", JSON.stringify(res.user))
      localStorage.setItem("userId", res.user.id)
    } else {
      ElMessage.error(res.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 初始化加载
onMounted(() => {
  loadVideos()
  getCate()
  window.addEventListener('scroll', handleScroll)
})

// 滚动加载
const handleScroll = () => {
  const scrollBottom = document.documentElement.scrollHeight -
      window.innerHeight -
      document.documentElement.scrollTop
  if (scrollBottom < 200 && !loading.value && hasMore.value) {
    // loadVideos()
  }
}


</script>

<style lang="scss" scoped>
.main-header {
  .header-content {
    display: flex;
    align-items: center;
    width: 100%;
    padding: 0 24px;

    .logo {
      flex-shrink: 0;
      margin-right: 30px;
    }

    .search-input {
      flex: 1;
      max-width: 500px;
      min-width: 200px;
    }
  }
}

.carousel {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.carousel-item {
  height: 100%;
  background-size: cover;
  background-position: center;
  position: relative;
}

.carousel-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
}

.carousel-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.carousel-desc {
  font-size: 16px;
  opacity: 0.9;
}

.video-categories {
  margin-bottom: 24px;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.category-tags {
  display: flex;
  gap: 10px;
  padding: 5px 0;
}

.category-tag {
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 16px;
  font-size: 14px;
  transition: all 0.3s ease;
  border: 1px solid #e7e7e7;
  background-color: #f7f7f7;
  user-select: none;
}

.category-tag:hover:not(.disabled) {
  background-color: #e5f2f8;
  color: #00a1d6;
  border-color: #00a1d6;
  transform: translateY(-1px);
}

.category-tag.active {
  background-color: #00a1d6;
  color: white;
  border-color: #00a1d6;
  box-shadow: 0 2px 8px rgba(0, 161, 214, 0.3);
}

.category-tag.disabled {
  cursor: not-allowed;
  opacity: 0.6;
  pointer-events: none;
}

.category-tag.disabled:hover {
  transform: none;
  background-color: #f7f7f7;
  color: inherit;
  border-color: #e7e7e7;
}

.video-main {
  padding: 20px;
  max-width: 100%;
  margin: 0 auto;
}

.video-content-container {
  min-height: 400px;
  position: relative;
  transition: all 0.3s ease;
}

.video-content {
  width: 100%;
}

.video-grid {
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .video-grid {
    margin: -6px;
    .el-col {
      padding: 6px !important;
    }
  }
}

// 淡入淡出动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.fade-enter-from {
  opacity: 0;
  transform: translateY(10px);
}

.fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background-color: #fff;
  border-radius: 8px;
  margin-top: 20px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  min-height: 200px;
  .loading-icon {
    font-size: 30px;
    color: #409eff;
  }
}
</style>
